import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Class that describe the Decode process of our solution.
 * This class implements the method that provide to convert in a correct format H = (V,E),the possible
 * solution of the minisat solver,that will consist on our solution founded has 
 * Hamiltonian path.Whenever the solution not exist we simply halt the execution
 * 
 * @author Scinetti,Trombini,Garcia Fernandez
 *
 */

public class Decoder {

    private Graph H;
	public Decoder() {
		this.H = new Graph();
	}

	/**
	 * Method that given a file containing the output of the minisat application,
	 * provide to retrieve all the Verticies and the Edge found in a correct graph
	 * format.
	 * @throws IOException When the minisat result produce an unsatisfiable problem
	 */
	
	
	public void decode() throws IOException {
		FileReader input = new FileReader(Main.PATH + Main.FILE_OUTPUT);
		BufferedReader bufRead = new BufferedReader(input);

		String line, fileText = ""; // String that holds current file line

		while ((line = bufRead.readLine()) != null) {
			fileText += line + "\n";
		}

		String[] variables,split = fileText.split("Model:");
        ArrayList<String> ham = new ArrayList<String>();
		
		if (split.length != 2) {
			bufRead.close();
			throw new IndexOutOfBoundsException(
					"There is no possible Hamiltonian path,"
							+ "therefore the problem is unsatisfiable");
		} else {
			     variables = split[1].split("\n");
			for (int i = 0; i < variables.length; i++) {
				if (variables[i].charAt(0) != Solver.NOT.charAt(0)) {
					ham.add(variables[i]);
				}
			}
			ham.remove(0);
		}
		bufRead.close();
		//create the vertex in a format Rule precise
		
		ArrayList<Integer> Hvertex = new ArrayList<Integer>();
		
		for(int i=0;i<ham.size();i++){
			for(int j=0;j<ham.size();j++){
				if(ham.get(j).endsWith("p"+(i+1))){
					Hvertex.add(Integer.parseInt((ham.get(j).split("p")[0]).substring(2)));
				}
			}
		}
		System.out.println(ham);
		H.addVertex(Hvertex);
		
	}

	/**
	 * Getter of the Hamiltonian Path
	 * @return the correct Hamiltoniann path 
	 */
	
	public Graph getHamiltonianPath() {
		return this.H;
	}

}
